package com.mjk.common.ai.service;


import com.mjk.common.ai.dto.KbItemEmbeddingDto;
import com.mjk.common.ai.entity.KnowledgeBaseEmbedding;
import com.mjk.common.ai.mapper.KnowledgeBaseEmbeddingMapper;
import com.mjk.common.ai.util.MPPageUtil;
import com.mjk.common.core.jdbc.bean.BeePage;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class KnowledgeBaseEmbeddingService {

    @Autowired
    private BeeDBService beeDBService;

    @Autowired
    private KnowledgeBaseEmbeddingMapper mapper;

    public List<KnowledgeBaseEmbedding> listByEmbeddingIds(List<String> embeddingIds) {
        BeeQueryWrapper wrapper = BeeQueryWrapper.getWrapper(KnowledgeBaseEmbedding.class).in(KnowledgeBaseEmbedding::getEmbeddingId, embeddingIds.stream().map(UUID::fromString).toList());
        return beeDBService.findManyByWrapper(wrapper);
    }

    public BeePage<KbItemEmbeddingDto> listByItemUuid(String kbItemUuid, int currentPage, int pageSize) {
        BeePage<KnowledgeBaseEmbedding> sourcePage = mapper.selectByItemUuid(new BeePage<>(currentPage, pageSize), kbItemUuid);
        BeePage<KbItemEmbeddingDto> result = new BeePage<>();
        MPPageUtil.convertToPage(sourcePage, result, KbItemEmbeddingDto.class, (source, target) -> {
            target.setEmbedding(source.getEmbedding().toArray());
            return target;
        });
        return result;
    }

    /**
     * 删除{kbItemUuid}这个知识库条目的向量
     *
     * @param kbItemUuid 知识库条目uuid
     * @return
     */
    public boolean deleteByItemUuid(String kbItemUuid) {
        return mapper.deleteByItemUuid(kbItemUuid);
    }

    public Integer countByKbUuid(String kbUuid) {
        return mapper.countByKbUuid(kbUuid);
    }
}
